/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JP_RegistraAccion.java
 *
 * Created on Jul 15, 2009, 4:51:39 PM
 */

package gui.Mantenimiento;

import delegate.GestionDelegate;
import controlacciones.ejb3.entity.TbCategoriaAccion;
import helper.JP_Utiles_PanelBotonesMantenimiento;
import helper.JP_Utiles_PanelModelo;
import helper.Utiles_MensajesDialogo;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Task;
import org.jdesktop.beansbinding.BindingGroup;

/**
 *
 * 
 */
public class JP_MantenimientoTbCategoriaAccion extends JP_Utiles_PanelModelo {
    

    /** Creates new form JP_RegistraAccion */
    public JP_MantenimientoTbCategoriaAccion() {
        inicializaComponentes();
    }

    private void inicializaComponentes(){
        initComponents();
        //Panel de Operaciones
        ArrayList alBotones = new ArrayList( 1 );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_NUEVO ) );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_MODIFICAR ) );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_ELIMINAR ) );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_GUARDAR ) );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_DESHACER ) );
        alBotones.add( new Integer( JP_Utiles_PanelBotonesMantenimiento.BOTON_CERRAR ) );

        jp_ope = new JP_Utiles_PanelBotonesMantenimiento( this, alBotones );
        jp_Operaciones.setLayout( new BorderLayout() );
        jp_Operaciones.add( jp_ope, BorderLayout.CENTER );
        cargaTabla();
        this.habilitarComponentes( false );
        jp_ope.getBtnNuevo().setEnabled( true );
        jp_ope.getBtnModificar().setEnabled( true);
        jp_ope.getBtnEliminar().setEnabled( true );
        jp_ope.getBtnGuardar().setEnabled(false);
        jp_ope.getBtnDeshacer().setEnabled( false );
        jp_ope.getBtnCerrar().setEnabled( true );
    }

    public void inicializaReferencias(){
       
    }

    private void cargaTabla(){        
        try {
            listaDatos = GestionDelegate.getInstance().getListaTbCategoriaAccion();
        } catch (Exception ex) {
            Logger.getLogger( JP_MantenimientoTbCategoriaAccion.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println( "Error al cargar la lista de Usuarios" );
        }

//        for( TbCategoriaAccion ca : listaDatos ){
//            System.out.println("TbCategoriaAccion: " + ca.getCodCatAccion() + " " + ca.getDescripcion());
//        }
        try{
            bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
            jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listaDatos, this.tbUsuarios );
            org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${codCatAccion}"));
            columnBinding.setColumnName("Cod Cat Accion");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descripcion}"));
            columnBinding.setColumnName("Descripcion");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            bindingGroup.addBinding(jTableBinding);

            org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tbUsuarios, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.codCatAccion}"), codCatAccionField, org.jdesktop.beansbinding.BeanProperty.create("text"));
            bindingGroup.addBinding(binding);
            //binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, tbUsuarios, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), codCatAccionField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
            //bindingGroup.addBinding(binding);

            binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tbUsuarios, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.descripcion}"), descripcionField, org.jdesktop.beansbinding.BeanProperty.create("text"));
            bindingGroup.addBinding(binding);
            //binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, tbUsuarios, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), descripcionField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
            //bindingGroup.addBinding(binding);
           
            bindingGroup.bind();
            }catch( Exception e ){
                Logger.getLogger( JP_MantenimientoTbCategoriaAccion.class.getName()).log(Level.SEVERE, null, e);
                System.out.println( "Error en el binding " + e.getMessage() );
            }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always re-generated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jp_Operaciones = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        tbUsuarios = new javax.swing.JTable();
        jp_DatosUsuario = new javax.swing.JPanel();
        codCatAccionLabel = new javax.swing.JLabel();
        codCatAccionField = new javax.swing.JTextField();
        descripcionLabel = new javax.swing.JLabel();
        descripcionField = new javax.swing.JTextField();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class).getContext().getResourceMap(JP_MantenimientoTbCategoriaAccion.class);
        jp_Operaciones.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jp_Operaciones.border.title"))); // NOI18N
        jp_Operaciones.setName("jp_Operaciones"); // NOI18N

        javax.swing.GroupLayout jp_OperacionesLayout = new javax.swing.GroupLayout(jp_Operaciones);
        jp_Operaciones.setLayout(jp_OperacionesLayout);
        jp_OperacionesLayout.setHorizontalGroup(
            jp_OperacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 459, Short.MAX_VALUE)
        );
        jp_OperacionesLayout.setVerticalGroup(
            jp_OperacionesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 41, Short.MAX_VALUE)
        );

        masterScrollPane.setName("masterScrollPane"); // NOI18N

        tbUsuarios.setName("tbUsuarios"); // NOI18N
        tbUsuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbUsuariosMouseClicked(evt);
            }
        });
        tbUsuarios.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbUsuariosKeyReleased(evt);
            }
        });
        masterScrollPane.setViewportView(tbUsuarios);

        jp_DatosUsuario.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jp_DatosUsuario.border.title"))); // NOI18N
        jp_DatosUsuario.setName("jp_DatosUsuario"); // NOI18N

        codCatAccionLabel.setText(resourceMap.getString("codCatAccionLabel.text")); // NOI18N
        codCatAccionLabel.setName("codCatAccionLabel"); // NOI18N

        codCatAccionField.setName("codCatAccionField"); // NOI18N
        codCatAccionField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                codCatAccionFieldKeyPressed(evt);
            }
        });

        descripcionLabel.setText(resourceMap.getString("descripcionLabel.text")); // NOI18N
        descripcionLabel.setName("descripcionLabel"); // NOI18N

        descripcionField.setName("descripcionField"); // NOI18N
        descripcionField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                descripcionFieldKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jp_DatosUsuarioLayout = new javax.swing.GroupLayout(jp_DatosUsuario);
        jp_DatosUsuario.setLayout(jp_DatosUsuarioLayout);
        jp_DatosUsuarioLayout.setHorizontalGroup(
            jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jp_DatosUsuarioLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(codCatAccionLabel)
                    .addComponent(descripcionLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(codCatAccionField, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                    .addComponent(descripcionField, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE))
                .addGap(22, 22, 22))
        );
        jp_DatosUsuarioLayout.setVerticalGroup(
            jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jp_DatosUsuarioLayout.createSequentialGroup()
                .addGroup(jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codCatAccionLabel)
                    .addComponent(codCatAccionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jp_DatosUsuarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descripcionLabel)
                    .addComponent(descripcionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jp_Operaciones, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE)
                    .addComponent(jp_DatosUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jp_DatosUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jp_Operaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tbUsuariosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbUsuariosKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_tbUsuariosKeyReleased

    private void tbUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbUsuariosMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_tbUsuariosMouseClicked

    private void codCatAccionFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codCatAccionFieldKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()== evt.VK_ENTER){
            this.descripcionField.requestFocus();
        }
    }//GEN-LAST:event_codCatAccionFieldKeyPressed

    private void descripcionFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_descripcionFieldKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()== evt.VK_ENTER){
            this.jp_ope.getBtnGuardar().requestFocus();
        }
    }//GEN-LAST:event_descripcionFieldKeyPressed

    private void limpiarComponentes(){
        this.codCatAccionField.setText( "" );
        this.descripcionField.setText( "" );
    }

    private void habilitarComponentes( boolean ban ){
        this.codCatAccionField.setEnabled( ban );
        this.descripcionField.setEnabled( ban );
    }

    public boolean isSaveNeeded() {
        return saveNeeded;
    }

    private void setSaveNeeded(boolean saveNeeded) {
        if (saveNeeded != this.saveNeeded) {
            this.saveNeeded = saveNeeded;
            firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
        }
    }

    public boolean isRecordSelected() {
        return tbUsuarios.getSelectedRow() != -1;
    }

    public void refrescar(){
        cargaTabla();
        this.limpiarComponentes();
        this.habilitarComponentes( false );
        jp_ope.getBtnNuevo().setEnabled( true );
        jp_ope.getBtnModificar().setEnabled( true );
        jp_ope.getBtnEliminar().setEnabled( true );
        jp_ope.getBtnGuardar().setEnabled( false );
        jp_ope.getBtnDeshacer().setEnabled( false );
        jp_ope.getBtnCerrar().setEnabled( true );
    }

    @Override
    public Task nuevo(){
        //return new Guarda(org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class));
        this.limpiarComponentes();
        this.habilitarComponentes( true );
        this.codCatAccionField.requestFocus();
        setSaveNeeded(true);
        this.ind = 0;
        jp_ope.getBtnNuevo().setEnabled( false );
        jp_ope.getBtnModificar().setEnabled( false );
        jp_ope.getBtnEliminar().setEnabled( false );
        jp_ope.getBtnGuardar().setEnabled(true);
        jp_ope.getBtnDeshacer().setEnabled( true );
        jp_ope.getBtnCerrar().setEnabled( true );
        return null;
    }

    @Override
    public Task modificar(){
        //return new Guarda(org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class));        
        obtenerDatosTabla();
        this.ind = 1;
        this.codCatAccionField.setEnabled( false );
        this.descripcionField.requestFocus();
        jp_ope.getBtnNuevo().setEnabled( false );
        jp_ope.getBtnModificar().setEnabled( false );
        jp_ope.getBtnEliminar().setEnabled( false );
        jp_ope.getBtnGuardar().setEnabled(true);
        jp_ope.getBtnDeshacer().setEnabled( true );
        jp_ope.getBtnCerrar().setEnabled( true );
        this.descripcionField.setEnabled( true );
        return null;
    }

    void obtenerDatosTabla(){
        try{
            int selected = this.tbUsuarios.getSelectedRow();
            if( selected > -1 ){
                TbCategoriaAccion t = this.listaDatos.get(tbUsuarios.convertRowIndexToModel(selected));
                this.codCatAccionField.setText( t.getCodCatAccion() );
                this.descripcionField.setText( t.getDescripcion() );
                this.ind = 1;
            }
        }catch( Exception ex ){
            System.out.println("Error al obtener tabla (obtenerDatosTabla):" + ex.getMessage());
        }
    }

    @Override
    public Task eliminar(){
        return new Elimina(org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class));
    }

    @Override
    public Task guardar() {
        return new Guarda(org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class));
    }
    
    @Override
    public Task deshacer() {
       limpiarComponentes();
       this.habilitarComponentes( false );
       jp_ope.getBtnNuevo().setEnabled( true );
       jp_ope.getBtnModificar().setEnabled( true);
       jp_ope.getBtnEliminar().setEnabled( true );
       jp_ope.getBtnGuardar().setEnabled(false);
       jp_ope.getBtnDeshacer().setEnabled( false );
       jp_ope.getBtnCerrar().setEnabled( true );
       return null;
    }

    @Override
    public Task cerrar() {
        this.cerrarPadre();
        return null;
    }
    
    private class Guarda extends org.jdesktop.application.Task<Object, Void> {
        Guarda(org.jdesktop.application.Application app) {
            super(app);
        }
        @Override protected Object doInBackground() {            
            guardarSegundoPlano();
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
            
        }
        @Override protected void finished() {
            setSaveNeeded(false);
        }
    }

    public void guardarSegundoPlano(){
        try{
            this.guardarCambios();           
            
        }catch( Exception ex ){
            ex.printStackTrace();
            Utiles_MensajesDialogo.mensajeFracaso( "Error" + ex.getMessage() );
        }
    }   
   
    //Metodos para guardar   
   
    private void  guardarCambios() throws Exception{
        String codCatAccion, descripcion;
        TbCategoriaAccion tbCategoriaAccion = new TbCategoriaAccion();
        codCatAccion = this.codCatAccionField.getText().trim();
        descripcion = this.descripcionField.getText().trim();
        
        if(verificarDatos(codCatAccion,descripcion )){
            tbCategoriaAccion.setCodCatAccion( codCatAccion );
            tbCategoriaAccion.setDescripcion(descripcion);

            if( ind == 0 ){
                this.insertaCategoriaAccion(tbCategoriaAccion);
            }else{
                this.modificaCategoriaAccion(tbCategoriaAccion);
            }
            Utiles_MensajesDialogo.mensajeExito();
            refrescar();
        }else{
            Utiles_MensajesDialogo.mensajeFracaso( "Datos inválidos" );
        }
        
    }

    private boolean verificarDatos(String codCatAccion, String descripcion ){
        if( codCatAccion.trim().equals( "" )){
            Utiles_MensajesDialogo.mensajeAlerta( " codCatAccion inválido " );
            return false;
        }
        if( descripcion.trim().equals( "" )){
            Utiles_MensajesDialogo.mensajeAlerta( " descripcion en blanco " );
            return false;
        }        
        return true;
    }

    private void insertaCategoriaAccion( TbCategoriaAccion tbCategoriaAccion ) throws Exception{
        GestionDelegate.getInstance().insertarCategoriaAccion( tbCategoriaAccion );
    }

    private void modificaCategoriaAccion( TbCategoriaAccion tbCategoriaAccion ) throws Exception{
        GestionDelegate.getInstance().actualizarCategoriaAccion(tbCategoriaAccion);
    }

    private class Elimina extends org.jdesktop.application.Task<Object, Void> {
        Elimina(org.jdesktop.application.Application app) {
            super(app);
        }
        @Override protected Object doInBackground() {
            jp_ope.getBtnGuardar().setEnabled(false);
            jp_ope.getBtnEliminar().setEnabled(false);
            eliminarSegundoPlano();
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {            
            jp_ope.getBtnEliminar().setEnabled(true);
        }
    }

    public void eliminarSegundoPlano(){
        try{
            this.eliminaUsuario( );
            Utiles_MensajesDialogo.mensajeExito();
            refrescar();
        }catch( Exception ex ){
            ex.printStackTrace();
            Utiles_MensajesDialogo.mensajeFracaso( "Error" + ex.getMessage() );
        }
    }

    //Metodos para eliminar
    private void eliminaUsuario( ) throws Exception{
        /*TbUsuario tbUsuario = new TbUsuario();
        tbUsuario.setLogUser( textlogUser.getText());
        SeguridadGestionDelegate.getInstance().sp_eliminarUsuario( tbUsuario );
*/

        int[] selected = this.tbUsuarios.getSelectedRows();
        List< TbCategoriaAccion> toRemove = new ArrayList<TbCategoriaAccion>(selected.length);
        for (int idx=0; idx<selected.length; idx++) {
            TbCategoriaAccion t = this.listaDatos.get(tbUsuarios.convertRowIndexToModel(selected[idx]));
            toRemove.add(t);            
            GestionDelegate.getInstance().eliminarCategoriaAccion( t );//      entityManager.remove(t);
        }
        listaDatos.removeAll(toRemove);
        setSaveNeeded(true);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField codCatAccionField;
    private javax.swing.JLabel codCatAccionLabel;
    private javax.swing.JTextField descripcionField;
    private javax.swing.JLabel descripcionLabel;
    private javax.swing.JPanel jp_DatosUsuario;
    private javax.swing.JPanel jp_Operaciones;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable tbUsuarios;
    // End of variables declaration//GEN-END:variables
    private JP_Utiles_PanelBotonesMantenimiento jp_ope;
    private BindingGroup bindingGroup;

    //Datos los cuales van a realizar la persistencia del objeto

    private org.jdesktop.swingbinding.JTableBinding jTableBinding;
    private List<TbCategoriaAccion> listaDatos;
    //private java.util.List<TbUsuario> list;

    private int ind = 0;//0 nuevo 1 actualizar
    private boolean saveNeeded;

}
